package cn.wen233.basic.utils;

import java.io.*;
import java.net.HttpURLConnection;

/**
 * Io控制工具类
 *
 * @author wenei
 * @date 2021-10-25 15:38
 */
public class IoUtils {

    /**
     * 将InputStream中的数据转化为字符串
     */
    public static String toString(InputStream inputStream, String encoding) throws IOException {
        if (inputStream == null) {
            return null;
        } else {
            return encoding == null ? toString(inputStream, "UTF-8") : toString(new InputStreamReader(inputStream, encoding));
        }
    }

    /**
     * 将Reader里面的数据转化为字符串
     */
    public static String toString(Reader reader) throws IOException {
        CharArrayWriter writer = new CharArrayWriter();
        copy(reader, writer);
        return writer.toString();
    }

    /**
     * 将Reader里面的数据复制到Writer中
     */
    public static long copy(Reader input, Writer output) throws IOException {
        char[] buffer = new char[4096];
        long count = 0;
        int n;
        for (;(n = input.read(buffer)) >= 0; count += n) {
            output.write(buffer, 0, n);
        }
        return count;
    }

    public static void closeQuietly(HttpURLConnection connection) {
        if (connection != null) {
            try {
                closeQuietly(connection.getInputStream());
            } catch (IOException e) {
            }
        }
    }

    public static void closeQuietly(InputStream input) {
        closeQuietly((Closeable) input);
    }

    public static void closeQuietly(OutputStream output) {
        closeQuietly((Closeable) output);
    }

    /**
     * 安静的关闭，不打印相关日志信息
     */
    public static void closeQuietly(Closeable closeable) {
        if (closeable != null) {
            try {
                closeable.close();
            } catch (IOException e) {

            }
        }
    }
}
